import os
from pypinyin import lazy_pinyin
from flask import (
    Blueprint, request, current_app, send_from_directory, request
)
from flask_login import current_user, login_required
from werkzeug.utils import secure_filename
from FileShare.models import loginfo, User
from FileShare.extensions import db

files_bp = Blueprint('files', __name__)

@files_bp.route('/uploads', methods=['POST'])
@login_required
def uploads():
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], current_user.username)
    if not os.path.isdir(file_path):
        os.makedirs(file_path)
    username_id = User.query.filter_by(username=current_user.username).first().id

    for file in request.files.getlist('file'):
        filename = secure_filename('_'.join(lazy_pinyin(file.filename)))
        file_path_uri = os.path.join(file_path, filename)
        loginfo1 = loginfo(username_id=username_id, ip_address=request.remote_addr, ops_type='upload', filename=os.path.join(current_user.username, filename))
        if not os.path.exists(file_path_uri):
            file.save(file_path_uri)
            db.session.add(loginfo1)
            db.session.commit()
            return 'success', 200
        else:
            return 'file already exist', 400
    return 'success', 200


@files_bp.route('/download/<path:filename>', methods=['GET'])
def download(filename):
    if not current_user.is_authenticated:
        username_id = 3
    else:
        username_id = User.query.filter_by(username=current_user.username).first().id
    loginfo1 = loginfo(username_id=username_id, ip_address=request.remote_addr, ops_type='download', filename=filename)
    db.session.add(loginfo1)
    db.session.commit()
    return send_from_directory(directory=current_app.config['UPLOAD_FOLDER'], filename=filename)

@files_bp.route('/delete/<path:filename>', methods=['GET'])
@login_required
def delete(filename):
    file_path_uri = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
    username_id = User.query.filter_by(username=current_user.username).first().id
    loginfo1 = loginfo(username_id=username_id, ip_address=request.remote_addr, ops_type='delete', filename=filename)
    db.session.add(loginfo1)
    db.session.commit()

    if os.path.exists(file_path_uri):
        os.remove(file_path_uri)
    return 'success', 200
